﻿/*
 * This file is part of CommunitySettlers.
 *
 * CommunitySettlers is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * CommunitySettlers is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with CommunitySettlers.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Author: Christoph Husse
 * 
 * Also checkout our homepage: http://communitysettlers.codeplex.com/
 */
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Drawing;

namespace SettlersEngine
{
    [Serializable]
    internal abstract class IBuildableObject : IPositionProvider
    {
        internal List<IResourceObject> m_Providers = new List<IResourceObject>();
        internal List<IResourceObject> m_Queries = new List<IResourceObject>();
        internal Double ProductionStartTime { get; set; }
        internal LinkedListNode<IBuildableObject> BuildableNode { get; set; }
        internal Int32 SettlersToSpawn { get; set; }
        internal LinkedListNode<ResourceAnimation> m_AnimationNode = null;
        internal Int32 CycleCounter = 1;

        public abstract Int64 ProductionElapsedMillis { get; }
        public System.Drawing.Point SpawnPoint { get; set; }
        public Int32 VisualWidth { get; private set; }
        public Int32 VisualHeight { get; private set; }
        public System.Drawing.Rectangle LockedBounds { get; private set; }
        public BuildingConfig Config { get; internal set; }

        public override IVisualObject UserContext
        {
            get
            {
                return base.UserContext;
            }
            set
            {
                base.UserContext = value;

                if (value != null)
                {
                    VisualWidth = ((IVisualSizedObject)UserContext).VisualWidth;
                    VisualHeight = ((IVisualSizedObject)UserContext).VisualHeight;
                    LockedBounds = ((IVisualSizedObject)UserContext).LockedBounds;
                }
            }
        }

        /// <summary>
        /// Gets or sets whether the building is built already.
        /// </summary>
        public Boolean IsCompleted { get; internal set; }
        /// <summary>
        /// Gets or sets whether the building is built already.
        /// </summary>
        public Boolean IsGraded { get; internal set; }
        /// <summary>
        /// Gets or sets a value between 0.0 and 1.0, where 1.0 indicates that building is completed.
        /// </summary>
        public Double BuildProgress { get; internal set; }
        /// <summary>
        /// Gets or sets a value between 0.0 and 1.0, where 1.0 indicates that grading is completed.
        /// </summary>
        public Double GradeProgress { get; internal set; }
        /// <summary>
        /// Gets or sets a value between 0.0 and 1.0, where 1.0 indicates a destroyed building.
        /// </summary>
        public Double Damage { get; internal set; }

        /// <summary>
        /// Gets or sets whether the production offset for buildings like farms and forester. By default it
        /// is set to (0,0). Chaning this value allows you, for example, to let the forester place wood on a relative location
        /// to his house.
        /// </summary>
        public System.Drawing.Point RangeOffset { get; set; }
        /// <summary>
        /// Gets or sets whether the building should start producing, if all resources are available.
        /// </summary>
        public Boolean IsEnabled { get; set; }
        /// <summary>
        /// Gets or sets whether the building is producing a resource.
        /// </summary>
        public abstract Boolean IsProducing { get; }
        public abstract Double ProductionProgress { get; }
        /// <summary>
        /// Gets or sets whether the building has at least one missing resource, required for production.
        /// </summary>
        public abstract Boolean CanProduce { get; }

        /// <summary>
        /// Gets or sets whether the building has at least one missing resource, required for production.
        /// </summary>
        public abstract Boolean HasMissingResources { get; }
        /// <summary>
        /// Gets or sets whether the building has too much produced resources and thus can't continue production.
        /// </summary>
        public abstract Boolean HasResourceOverflow { get; }

        public ReadOnlyCollection<IResourceObject> Providers { get; internal set; }
        public ReadOnlyCollection<IResourceObject> Queries { get; internal set; }
        public ReadOnlyCollection<ResourceAnimationStep> AnimationSteps { get; internal set; }

        public event DNotifyHandler<IBuildableObject> OnGradingCompleted;
        public event DNotifyHandler<IBuildableObject> OnBuildingCompleted;
        public event DNotifyHandler<IBuildableObject> OnDamaged;

        public abstract event DNotifyHandler<IBuildableObject> OnProductionStarted;
        public abstract event DNotifyHandler<IBuildableObject> OnProductionReady;


        internal IBuildableObject(RuntimeMap inParent, int inTypeIndex, CyclePoint inInitialPosition)
            : base(inParent, inTypeIndex, inInitialPosition)
        {
            Providers = new ReadOnlyCollection<IResourceObject>(m_Providers);
            Queries = new ReadOnlyCollection<IResourceObject>(m_Queries);
            Config = Map.GetBuildingConfig(inTypeIndex);
        }

        internal void RequestStartProduction()
        {

        }

        internal abstract void StartProduction();

        internal abstract void CompleteProduction();

        internal static IBuildableObject Create(BuildingType inBuildingType, RuntimeMap inMap, int inTypeIndex, CyclePoint inInitialPosition)
        {
            switch (inBuildingType)
            {
                case BuildingType.Default: return new DefaultBuilding(inMap, inTypeIndex, inInitialPosition);
                default:
                    throw new ArgumentException();
            }
        }
    }

    internal partial class RuntimeMap
    {
        public IBuildableObject CreateBuildingPreview(int inTypeIndex)
        {
            BuildingConfig config = BuildingConfigs[inTypeIndex];
            IBuildableObject obj = IBuildableObject.Create(config.BuiltinType, this, inTypeIndex, new CyclePoint(0, 0));
            IVisualSizedObject sized;

            obj.UserContext = sized = Factory.CreateBuilding(this, obj);
            obj.Config = config;

            return obj;
        }

        internal bool AddBuilding(IBuildableObject inBuildable)
        {
            if (!BuildingConfigs.ContainsKey(inBuildable.TypeIndex))
                throw new ArgumentException("Building type index " + inBuildable.TypeIndex + " is unknown.");

            inBuildable.Config = BuildingConfigs[inBuildable.TypeIndex];

            if (!Grid.CanPlaceObject(inBuildable))
                return false;

            Grid.Register(inBuildable);

            // add resources
            Point pos = inBuildable.GridPosition;
            BuildingConfig config = inBuildable.Config;
            List<ResourceAnimationStep> animSteps = new List<ResourceAnimationStep>();

            foreach (var resCfg in (from e in config.ResourceStacks orderby e.QualityIndex descending select e))
            {
                IResourceObject resObj;
                System.Windows.Point resPosShift = new System.Windows.Point(inBuildable.Position.X + resCfg.DoublePosition.X, inBuildable.Position.Y + resCfg.DoublePosition.Y);

                // TODO: validate stack position
                CyclePoint resPos = new CyclePoint()
                {
                    X = resPosShift.X,
                    Y = resPosShift.Y,
                };

                if (resCfg.Type == Resource.Max)
                    continue;

                if (resCfg.Direction == StackDirection.Outgoing)
                    resObj = IResourceObject.CreateAsProvider(this, resCfg.Type, resPos);
                else
                    resObj = IResourceObject.CreateAsQuery(this, resCfg.Type, resPos);

                resObj.MaxStackSize = resCfg.MaxStackSize;

                ResourceAnimationStep step = new ResourceAnimationStep()
                {
                    TimeOffset = resCfg.TimeOffset,
                    Resource = resObj,
                    Direction = resCfg.Direction,
                    CycleCount = resCfg.CycleCount,
                    QualityIndex = resCfg.QualityIndex,
                };

                if (resCfg.Direction == StackDirection.Outgoing)
                {
                    AddResource(resObj);
                    inBuildable.m_Providers.Add(resObj);
                    animSteps.Add(step);
                }
                else
                {
                    AddResource(resObj);
                    inBuildable.m_Queries.Add(resObj);
                    animSteps.Add(step);
                }
            }

            // TODO: validate CycleCount and QualityIndex
            /*
             * If CycleCount is used or QualityIndex, then all queries are expected to have distinct QualityIndices
             * as well as a TimeOffset of zero. 
             */

            // setup spawn point
            IEnumerable<ResourceStackConfig> spwanPoints = from e in inBuildable.Config.ResourceStacks where e.Type == Resource.Max select e;

            if (spwanPoints.Count() > 0)
            {
                System.Windows.Point tmp = spwanPoints.First().DoublePosition;

                inBuildable.SpawnPoint = new Point((int)tmp.X, (int)tmp.Y);
            }

            // spawn settlers if any
            if (inBuildable.Config.SettlerCount > 0)
                inBuildable.SettlersToSpawn = inBuildable.Config.SettlerCount;

            /*
             * If quality indices are used:
             * 
             *      TimeOffset will always be null. The following ensures that anim steps are ordered ascending by quality index,
             *      resulting in resources with a lower QI are used first.
             *      
             * If no quality indices are used:
             * 
             *      Steps are ordered ascending by TimeOffset.
             */
            inBuildable.AnimationSteps = new ReadOnlyCollection<ResourceAnimationStep>(animSteps.OrderBy(e => (e.TimeOffset + e.QualityIndex)).ToList());

            return true;
        }

        internal void RemoveBuilding(IBuildableObject inBuildable)
        {
            Grid.Unregister(inBuildable);

            foreach (var prov in inBuildable.Providers)
            {
                RemoveResource(prov);
            }

            inBuildable.m_Providers.Clear();

            foreach (var query in inBuildable.Providers)
            {
                RemoveResource(query);
            }

            inBuildable.m_Queries.Clear();
        }

        private void ProcessBuildingProduction()
        {
            foreach (IBuildableObject buildable in Grid.Buildings)
            {
                if (buildable.HasMissingResources || buildable.HasResourceOverflow)
                {
                    // alert
                }
                else if(buildable.CanProduce)
                {
                    if (!buildable.IsProducing)
                        buildable.StartProduction();
                }

                if (buildable.SettlersToSpawn > 0)
                {
                    IMovableObject carrier = new IMovableObject(
                        this,
                        MoveableType.Carrier,
                        CyclePoint.FromGrid(buildable.SpawnPoint.X + buildable.Position.X, buildable.SpawnPoint.Y + buildable.Position.Y));

                    if (!Grid.CanPlaceObject(carrier))
                        continue;

                    Grid.Register(carrier);

                    Grid.SetMovablePath(carrier, new Point(carrier.GridPosition.X, carrier.GridPosition.Y + 5));
                    
                    buildable.SettlersToSpawn = 0;
                }
            }
        }
    }
}
